#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>

using namespace std;

/**
 * 文件随机读写
 * @return
 */
struct student {
    char name[10];
    int num;
    int age;
    char sex;
};

student stu[5] = {
        {"Li", 1001, 11, 'M'},
        {"Zhang", 1002, 13, 'F'},
        {"Wang", 1003, 15, 'M'},
        {"Zhao", 1004, 16, 'F'},
        {"Liu", 1005, 13, 'M'}
};

int main() {
    //char a[10], b[10];
    //fstream iofile("file.dat", ios::in | ios::out);
    //if (!iofile) {
    //    cerr << "open error" << endl;
    //    exit(1);
    //}
    //cout << "enter 10 integer number:" << endl;
    //for (int i = 0; i < 10; i++) {
    //    cin >> a[i];
    //    iofile << a[i] << " "; //保存是ask码值
    //    //iofile.write(&a[i], sizeof(a[i])); //一般用于读字符
    //}
    //cout << "The numbers have been writen to file." << endl;
    //iofile.seekg(0, ios::beg); //0代表位移量可正可负  ios::beg代表参考位置 为开头
    //for (int i = 0; i < 10; ++i) {
    //    iofile >> b[i];
    //    cout << b[i] << " ";
    //}
    //cout << endl;
    //iofile.close();

    student stu[5];

    fstream iofile("file1.dat", ios::in | ios::out | ios::binary);
    for (int i = 0; i < 5; ++i) {
        iofile.write((char *) &stu[i], sizeof(stu[i]));
    }
    student stud1[5];
    for (int i = 0; i < 5; i += 2) {
        iofile.seekg(i * sizeof(stud1[i]), ios::beg);
        iofile.read((char *) &stud1[i / 2], sizeof(stu[0])); //保存到stud1的1 2 3的位置
        cout << stud1[i]; //假设输出
    }
    stu[2].num = 1001;
    strcpy(stu[2].name, "WU");
    stu[2].sex = 'M';
    iofile.seekg(2 * sizeof(stu[0]), ios::beg); //定位到第三个对象的位置

    iofile.write((char *) &stu[2], sizeof(stu[2])); //修改完之后再保存到文件中

    iofile.seekg(0, ios::beg); //重新定位开头

    for (int i = 0; i < 5; ++i) {
        iofile.read((char *) &stu[i], sizeof(stu[i]));
        cout << stu[i].name;
    }

    iofile.close();
    return 0;
}